from flask import g
from flask import request
from flask import session, jsonify

from info import constants
from info import redis_store
from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
import logging
from  flask import current_app
from flask import render_template



# 获取新闻列表
# 请求路径:/newslist
# 请求方式:GET
# 请求参数:cid,page,per_page
# 返回值:data数据
"""
首页新闻列表获取思路
　　１获取参数
    ２参数类型转换int类型，为分页做准备
    ３分页查询
    ４获取分页对象身上属性，总页数，当前页，当前页对象列表
    ５将对象列表转成字典列表
    ６拼接数据，返回响应
"""""
@index_blue.route('/newslist')

def news_list():
    # 　１获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")
    # ２参数类型转换int类型，为分页做准备
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10
    # ３分页查询
    try:
        # 判断是否分类id = 1
        query_condition = ""
        if cid != "1":
            query_condition = News.category_id == cid
        paginate = News.query.filter(query_condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno=RET.DBERR,errmsg="新闻获取失败")

    # ４获取分页对象身上属性，总页数，当前页，当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.pages
    items = paginate.items
    # ５将对象列表转成字典列表
    newsList = []
    for item in items:
        newsList.append(item.to_dict())
    # ６拼接数据，返回响应
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "newsList":newsList

    }
    return jsonify(errno=RET.OK,errmsg="获取成功",totalPage=totalPage,currentPage=currentPage,newsList=newsList)




@index_blue.route('/', methods=["GET", "POST"])
@user_login_data
def show_index():
    # 测试redis存储数据
    # redis_store.set("name", "laolang"),
    # print(redis_store.get("name"))

    #     测试session存储信息
    # session["product"] = "lenovo"
    # print(session.get("product"))

    # 使用日志模块输出内容
    # logging.debug("调试信息")
    # logging.info("详细信息")
    # logging.warning("警告信息")
    # logging.error("错误信息")

    # 使用current_app输出日志  和上面输出比较有华丽分割线
    # current_app.logger.debug("调试信息2")
    # current_app.logger.info("详细信息2")
    # current_app.logger.warning("警告信息2")
    # current_app.logger.error("错误信息2")
    # 获取用户登陆状态
    # user_id = session.get("user_id")
    # # 获取用户登陆数据
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 携带用户数据渲染到页面
    # if user:
    #     user_dict={
    #         "id":user.id,
    #         "nick_name":user.nick_name
    #     }
    # 根据浏览量查询前十条新闻
    try:
        news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询失败")

    # 将新闻对象列表　转成字典列表
    click_news_list = []
    for new in news:
        click_news_list.append(new.to_dict())

    # 查询所有的分类列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="分类查询失败")
    # 将分类对象列表转成字典
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    # 携带用户数据渲染到页面中
    data = {
        # 如果user有值返回左边内容 否则返回右边
        "user_info": g.user.to_dict() if g.user else "",
        "click_news_list": click_news_list,
        "category_list": category_list

    }
    return render_template("news/index.html", data=data)


# 网站logo处理
@index_blue.route("/favicon.ico")
def web_logo():
    return current_app.send_static_file("news/favicon.ico")
